package util;

import javax.swing.text.*;
import java.awt.Toolkit;

public class TextFieldMaxLenth extends PlainDocument {

    protected int maxLength;

    public TextFieldMaxLenth(int maxLength) {
        this.maxLength = maxLength;
    }

    public int maxLength() {
        return maxLength;
    }

    public void insertString(int offs, String str, AttributeSet a) throws
            BadLocationException {
        if (str == null) {
            return;
        }
        int strLen = str.length();
        if (strLen == 0) {
            return;
        }
        int len = getLength();
        if (strLen + len > maxLength) {
            Toolkit.getDefaultToolkit().beep();
            str = str.substring(0, maxLength - len);
        }
        super.insertString(offs, str, a);
    }
}
